<template>
  <el-dialog
    v-model="dialogVisible"
    title="短信验证码"
    width="30%"
    :close-on-click-modal="false"
    :show-close="false"
    center
  >
    <div class="sms-code-container">
      <el-alert
        title="验证码已发送"
        type="success"
        :closable="false"
        show-icon
      >
        <template #default>
          <p>验证码已发送到手机: {{ formatPhone(phone) }}</p>
        </template>
      </el-alert>
      
      <div class="code-display">
        <h2>您的验证码是：</h2>
        <div class="code-number">{{ code }}</div>
        <p class="code-tip">此验证码仅用于测试，实际应用中将通过短信发送</p>
      </div>
      
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirmCode">
          确认使用
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  phone: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:visible', 'confirm'])

// 生成6位随机验证码
const generateCode = () => {
  return Math.floor(100000 + Math.random() * 900000).toString()
}

const code = ref(generateCode())
const dialogVisible = ref(false)

// 监听visible属性变化
// 格式化手机号，中间4位显示为*
const formatPhone = (phone: string) => {
  if (!phone || phone.length !== 11) return phone
  return phone.substring(0, 3) + '****' + phone.substring(7)
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  emit('update:visible', false)
}

// 确认使用验证码
const confirmCode = () => {
  emit('confirm', code.value)
  closeDialog()
}

// 使用watch监听props.visible的变化
import { watch } from 'vue'
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (dialogVisible.value) {
    code.value = generateCode()
  }
}, { immediate: true })
</script>

<style scoped>
.sms-code-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
}

.code-display {
  margin: 20px 0;
  text-align: center;
  width: 100%;
}

.code-number {
  font-size: 32px;
  font-weight: bold;
  letter-spacing: 5px;
  color: #667eea;
  background: linear-gradient(135deg, #F0F9FF 0%, #E0E7FF 100%);
  padding: 15px;
  border-radius: 8px;
  margin: 15px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.code-tip {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}

.dialog-footer {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>